<?
/******************************************
* ZEMPLATE
* ---------------------------
* A PHP template by Zenyai
* 
* For more information: http://code.google.com/p/zemplate/
* This project is under an open source license (Apache License, Version 2.0)
* http://www.apache.org/licenses/LICENSE-2.0
*
*******************************************/

// the main zemplate class
class Zemplate {
    protected $file;
    protected $values = array();
	protected $head = array();
	protected $body = array();
	protected $i = 0;
	
	// constructor
    public function __construct($file) {
		require_once("config.php"); // to get the template name
        $this->file = "templates/" . $template_name . "/" . $file;
    }
	
	// set key and value for further replacement
	public function set($key, $value) {
		$this->values[$key] = $value;
	}
	
	// call function from function folder
	public function callFunc($function, $loadin, $var){
		require_once('functions/' . $function . '.functions.php'); // function must be in zemplate/functions folder and with the (funcname).functions.php format
		
		//check if you want to load in head
		if($loadin == "head"){
			$new = new $function($var);
			
			// add numeric to function LoadJavascript() and LoadCSS() so that it can be load repeatedly
			if($function == "LoadJavascript"){
			$javafuncname = "LoadJavascript" . $this->i;
			$this->head[$javafuncname] = $new;
			$this->i++;
			}else if($function == "LoadCSS"){
			$javafuncname = "LoadCSS" . $this->i;
			$this->head[$javafuncname] = $new;
			$this->i++;
			} else {
			$this->head[$function] = $new; // normal function
			}
		}
		// else load in body
		if($loadin == "body"){
			$new = new $function($var);
			$this->body[$function] = $new;
		}
		
	}
  
	// output the template
	public function output() {
		if (!file_exists($this->file)) {
			return "Cannot find template file";
		}
		$output = file_get_contents($this->file);
  
		foreach ($this->values as $key => $value) {
			$tagToReplace = "[@$key]";
			$output = str_replace($tagToReplace, $value, $output);
		}
		
		include("config.php");
		$tagToReplace = "[@+template]";
		$template_place = "templates/" . $template_name;
		$output = str_replace($tagToReplace, $template_place, $output);
		
		foreach ($this->head as $function => $new) {
			$tagToReplace = "</head>";
			$output = str_replace($tagToReplace, $new->load() . "\n</head>", $output);
		}
		
		foreach ($this->body as $function => $new) {
			$tagToReplace = "</body>";
			$output = str_replace($tagToReplace, $new->load() . "\n</body>", $output);
		}
		
		
		$output = preg_replace("/<!--(.|\s)*?-->/", "", $output); // hide html comment tag from browser
		
		
		return $output;
	}
	
	// credit: nunof from broculos.net
}

?>